<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Apply;
use app\common\model\Article;
use app\common\model\Attr;
use app\common\model\Collect;
use app\common\model\Json;
use app\common\model\Look;
use app\common\model\Search;
use app\common\model\Users;
use app\common\model\Zixun;
use think\Config;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public $openid = '';
    public $uid = '';
    public $fws = [5,14,15];//服务商
    public $jypt = [6,17,18];//交易平台
    public function __construct()
    {
        parent::__construct();
        $this->openid = input('token','');
        $this->uid = Users::where(['openid'=>$this->openid])->value('id');
        $actionname = strtolower($this->request->action());
        if(!in_array($actionname,['config','main']) && !$this->uid){
            $this->error('请先登录');die;
        }
        $ids = Attr::where('attr_id','in',$this->fws)->column('id');
        $this->fws = array_merge($this->fws,$ids);
        $ids = Attr::where('attr_id','in',$this->jypt)->column('id');
        $this->jypt = array_merge($this->jypt,$ids);
    }

    /**
     * 首页
     *
     */
    // public function index()
    // {
    //     $this->success('请求成功');
    // }
    public function userinfo()
    {
        $info = Users::where(['openid'=>$this->openid])->find();
        $this->success('ok',$info);
    }


    public function edituserinfo()
    {
        $nickname = input('nickname');
        if(mb_strlen($nickname,'utf8') > 8){
            $this->error('昵称最长8个字');die;
        }
        Users::where(['openid'=>$this->openid])->update(['name'=>$nickname]);
        $this->success('修改成功');
    }

    public function avatar()
    {
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }
        Users::where(['openid'=>$this->openid])->update(['image'=>$attachment->url]);
        $this->success(__('Uploaded successful'), ['url' => $attachment->url]);
    }

      /*获取access_token,不能用于获取用户信息的token*/
  public  function getAccessToken()
  {
      $appid = Config::get('site.appid');
      $secret = Config::get('site.appsecret');

      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";
      $ch = curl_init();
      curl_setopt($ch,CURLOPT_URL,$url);
      curl_setopt($ch,CURLOPT_HEADER,0);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
      $res = curl_exec($ch);
      curl_close($ch);
      return $res;
  }
  //图片合法性验证
  public function http_request($url, $data = null)
  {
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

      if (!empty($data)) {
          curl_setopt($curl, CURLOPT_POST, TRUE);
          curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
          curl_setopt($curl, CURLOPT_HTTPHEADER, array(
              'Content-Type: application/json'
          ));
      }
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
      $output = curl_exec($curl);
      curl_close($curl);
      return $output;
      exit();
  }
  //  获取手机号
  public function setphone(){
      $tmp = self::getAccessToken();
      $tmptoken = json_decode($tmp,1);
      $token = isset($tmptoken['access_token']) ? $tmptoken['access_token'] : '';
      $data['code'] = input('code','cd666e0ee4ba4ef0a3e34a852dca4561a1dff72bfb26ac4955b8f40ccd39d6ca');
      $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
      $info = $this->http_request($url,json_encode($data),'json');
      // 一定要注意转json，否则汇报47001错误
      $tmpinfo = json_decode($info,1);
      $code = isset($tmpinfo['errcode']) ? $tmpinfo['errcode'] : 1;
      $phone_info = isset($tmpinfo['phone_info']) ? $tmpinfo['phone_info'] : '';
      //手机号
      $phoneNumber = isset($phone_info['phoneNumber']) ? $phone_info['phoneNumber'] : '';
      if($code == '0'){
        Users::where(['id'=>$this->uid])->update(['mobile'=>$phoneNumber]);
        $this->success('ok',['phone'=>$phoneNumber]);
      }else{
        $this->error('失败');
      }

  }


    public function config(){
        $info = [];
        $info['name'] = Config::get('site.name');
        $info['logo_image'] = Config::get('site.logo_image');
        $info['top_image'] = Config::get('site.top_image');
        $info['about_us'] = Config::get('site.about_us');
        $info['phone'] = Config::get('site.phone');
        $info['main'] = Config::get('site.main');
        // $info['zixun'] = Config::get('site.zixun');
        // $info['jine'] = Config::get('site.jine');
        // $info['date'] = Config::get('site.date');
        $info['company'] = Config::get('site.company');
        $info['address'] = Config::get('site.address');
        $this->success('ok',$info);
    }

    private function getsons($attr_id){
        $list = Attr::where(['attr_id'=>$attr_id])->column('id');

        foreach($list as $v){
            $tmp = Attr::where(['attr_id'=>$v])->column('id');
            $list = array_merge($list,$tmp);
        }
        return array_merge($list,[$attr_id]);
    }

    public function main(){
        $attr = Attr::where(['attr_id'=>['>',0],'top_switch'=>1])->order('weigh','desc')->limit(5)->select();
        $ids = $this->fws;
        foreach($attr as $k=>$v){
            $limit = 3;
            switch($v['id']){
                case 3:
                case 4:
                    $limit = 1;
                break;
                case 6:
                    $limit = 2;
                break;
            }
            $sons = self::getsons($v['id']);
            $tmp = Article::where(['attr_id'=>['in',$sons],'top_switch'=>1])->limit($limit)->select();
            foreach($tmp as $kk=>$vv){
                if(in_array($vv['attr_id'],$ids)){
                    $tmp[$kk]['p_id'] = 5;
                }elseif(in_array($vv['attr_id'],$this->jypt)){
                    $tmp[$kk]['p_id'] = 6;
                }else{
                    $tmp[$kk]['p_id'] = 0;
                }
            }
            $attr[$k]['list'] = $tmp;
        }
        $this->success('ok',$attr);
    }
    
    public function article()
    {
        $id = input('id',0);
        $info = Article::where(['id'=>$id])->find();
        if(Look::where(['users_id'=>$this->uid,'article_id'=>$id])->count() == 0){
            Look::insert(['users_id'=>$this->uid,'article_id'=>$id]);
        }
        $info['collect'] = Collect::where(['users_id'=>$this->uid,'article_id'=>$id])->count();
        $info['apply'] = Apply::where(['users_id'=>$this->uid,'article_id'=>$id])->count();
        $info['question'] = Json::where('id','in',explode(',',$info['json_ids']))->limit(5)->select();
        $ids = $this->fws;
        if(in_array($info['attr_id'],$ids)){
            $info['p_id'] = 5;
        }elseif(in_array($info['attr_id'],$this->jypt)){
            $info['p_id'] = 6;
        }else{
            $info['p_id'] = 0;
        }
        $this->success('ok',$info);
    }

    public function articlelist()
    {
        $where = [];
        $id = input('id',0);
        if($id){
            $where['attr_id'] = $id;
        }
        $search = input('search','');
        $where['name'] = ['like',"%$search%"];
        if($search){
            Search::insert(['users_id'=>$this->uid,'search'=>$search]);
        }
        $list = Article::where($where)->order('weigh','desc')->paginate(10)->each(function($item){
            $ids = $this->fws;
            if(in_array($item['attr_id'],$ids)){
                $item['p_id'] = 5;
            }elseif(in_array($item['attr_id'],$this->jypt)){
                $item['p_id'] = 6;
            }else{
                $item['p_id'] = 0;
            }
        });
        $this->success('ok',$list);
    }
    public function attr()
    {
        $id = input('id',-1);
        $list = Attr::where(['attr_id'=>$id])->order('weigh','desc')->select();
        foreach($list as $k=>$v){
            $list[$k]['sons'] = Attr::where(['attr_id'=>$v['id']])->order('weigh','desc')->select();
        }
        $this->success('ok',$list);
    }
    public function attrinfo()
    {
        $id = input('id');
        $info = Attr::where(['id'=>$id])->find();
        $this->success('ok',$info);
    }

    public function zixun(){
        $insert = [
            'name'=>input('name'),
            'mobile'=>input('mobile'),
            'q_1'=>input('q_1'),
            'q_2'=>input('q_2'),
            'q_3'=>input('q_3'),
            'q_4'=>input('q_4'),
            'q_5'=>input('q_5')
        ];
        Zixun::insert($insert);
        $this->success('ok');
    }
    public function collect(){
        $id = input('id');
        $type = input('type',1);
        if($type == 1){
            Collect::insert(['users_id'=>$this->uid,'article_id'=>$id]);
        }else{
            Collect::where(['users_id'=>$this->uid,'article_id'=>$id])->delete();
        }
        $this->success('ok');
    }
    public function apply(){
        $id = input('id');
        Apply::insert(['users_id'=>$this->uid,'article_id'=>$id,'create_time'=>time()]);
        $this->success('ok');
    }
    public function searchlog(){
        $list = Search::where(['users_id'=>$this->uid])->order('id','desc')->limit(6)->select();
        $this->success('ok',$list);
    }
    public function delsearchlog(){
        $list = Search::where(['users_id'=>$this->uid])->delete();
        $this->success('ok',$list);
    }
    public function applylist(){
        $list = Apply::alias('l')
                    ->field('a.name,a.subtitle,l.create_time,l.enum,l.article_id')
                    ->where(['users_id'=>$this->uid])
                    ->join('article a','a.id=l.article_id','left')
                    ->paginate(10);
        $this->success('ok',$list);
    }
    public function looklist(){
        $type = input('type','产品');
        $list = Look::alias('l')
                    ->field('a.*')
                    ->join('article a','a.id=l.article_id')
                    ->where(['l.users_id'=>$this->uid,'enum'=>$type])
                    ->paginate(10)->each(function($item){
                        $ids = $this->fws;
                        if(in_array($item['attr_id'],$ids)){
                            $item['p_id'] = 5;
                        }elseif(in_array($item['attr_id'],$this->jypt)){
                            $item['p_id'] = 6;
                        }else{
                            $item['p_id'] = 0;
                        }
                    });
        $this->success('ok',$list);
    }
    public function collectlist(){
        $type = input('type','产品');
        $list = Collect::alias('l')
                    ->field('a.*')
                    ->join('article a','a.id=l.article_id')
                    ->where(['l.users_id'=>$this->uid,'enum'=>$type])
                    ->paginate(10)->each(function($item){
                        $ids = $this->fws;
                        if(in_array($item['attr_id'],$ids)){
                            $item['p_id'] = 5;
                        }elseif(in_array($item['attr_id'],$this->jypt)){
                            $item['p_id'] = 6;
                        }else{
                            $item['p_id'] = 0;
                        }
                    });
        $this->success('ok',$list);
    }
}
